<?php
/**
 * User: FDG348
 * Date: 2018/2/8
 * Time: 11:05
 * 
 * 修改历史
 * 修改时间：2018/2/11
 * 修改人：lizenan
 * 修改功能：【后台需求】商城导览/商城导览增加搜索：品牌名称搜索
 * 任务ID：513
 * 
 * 修改历史
 * 修改时间：2018/2/12
 * 修改人：lizenan
 * 修改功能：【后台需求】商城导览/商城导览添加/修改界面去除品牌图片Alt和手机品牌图片Alt
 * 任务ID：515
 */
namespace backend\controllers;

use Yii;
use backend\models\UploadForm;
use yii\web\AdminController;
use backend\models\BrandCategory;
use backend\models\Brand;
use backend\models\BrandPlus;
use common\helps\tools;
use backend\models\FloorCategory;

class ShoppingMallController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'ShoppingMall';
    
    public function actionIndex(){
        $model = new UploadForm();
        $brand_category = BrandCategory::find()->where('use_flg='.BrandCategory::STATUS_ENABLE)->asArray()->all();
        return $this->render('index',[
            'model'=>$model,
            'brand_category'=>$brand_category,
            'mall_floor'=>$GLOBALS['SHOPPING_MALL_FLOOR'],
        ]);
    }
    
    public function actionGetBrand(){
        $data = Yii::$app->request->post();
        $brand = Brand::find();
		//add by lizenan 20180211 【后台需求】商城导览/商城导览增加搜索：品牌名称搜索 513 start
        $brand_name = trim($data['brand_name']);
        if ($brand_name){
            $brand = $brand->where(['like','brand_name',$brand_name]);
        }
		//add by lizenan 20180211 【后台需求】商城导览/商城导览增加搜索：品牌名称搜索 513 start
        $count = $brand->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $brand->offset($data['start'])->limit($data['length'])->orderBy(
            [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
        $brand_id = array_column($list, 'id');
        $brand_plus = BrandPlus::find()->where(['brand_id'=>$brand_id])->asArray()->all();
        $brand_plus_list = [];
        if (is_array($brand_plus) && count($brand_plus) > 0)foreach ($brand_plus as $brand_plus_val){
            $brand_plus_list[$brand_plus_val['brand_id']][] = $brand_plus_val;
        }
        if (is_array($list) && count($list) > 0)foreach ($list as &$list_val){
            $plus = tools::arrayHasValue($brand_plus_list,$list_val['id']) ? $brand_plus_list[$list_val['id']] : [];
            $floor = $brand_category_name = [];
            if (is_array($plus) && count($plus) > 0)foreach ($plus as $plus_val){
                if (intval($plus_val['type']) == 1){
                    $floor[] = $plus_val['floor'];
                }else{
                    $brand_category_name[] = $plus_val['brand_category_name'];
                }
            }
            $list_val['floor'] = count($floor) > 0 ? implode('/', $floor) : '';
            $list_val['brand_category_name'] = count($brand_category_name) > 0 ? implode('/', $brand_category_name) : '';
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }
    
    public function actionChangeBrandStatus()
    {
        $data_now = array();
        $model = new Brand();
        $data = Yii::$app->request->post();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $hot_sale_where = ['id'=>$data['id']];
        $ret = $model::updateAll($data_now,$hot_sale_where);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionGetBrandDetail(){
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $brand = Brand::find()->joinWith('brandPlus')->where(['j_brand.id' => $id])->asArray()->one();
        $brand_plus = tools::arrayHasValue($brand,'brandPlus') ? $brand['brandPlus'] : [];
        $brand['floor_num'] = count($brand_plus) > 0 ? array_values(array_column($brand_plus, 'floor_num')) : [];
        $brand['brand_category_id'] = count($brand_plus) > 0 ? array_values(array_column($brand_plus, 'brand_category_id')) : [];
        $this->retJson($brand,200);
    }
    
    public function actionSaveBrand(){
        $brand = new Brand();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $data = Yii::$app->request->post();
            $brand_name = $data['brand_name'];
            if (!$brand_name){
                throw new \Exception('请填写品牌名称');
            }
            $sort = $data['sort'];
            $floor = tools::arrayHasValue($data,'floor') ? $data['floor'] : [];
            $brand_category = tools::arrayHasValue($data,'brand_category') ? $data['brand_category'] : [];
            $eliminate_val = '-1';
            if (count($floor) > 0){
                $key_1 = array_search($eliminate_val, $floor);
                if ($key_1 !== false){
                    unset($floor[$key_1]);
                }
            }
            if (count($brand_category) > 0){
                $key_2 = array_search($eliminate_val, $brand_category);
                if ($key_2 !== false){
                    unset($brand_category[$key_2]);
                }
            }
            if (count($floor) == 0 && count($brand_category) == 0){
                throw new \Exception('请至少选择一个楼层或品牌分类');
            }
            $brand_img = $data['brand_img'];
            if (!$brand_img){
                throw new \Exception('请上传品牌图片');
            }
            $brand_img_wap = $data['brand_img_wap'];
            if (!$brand_img_wap){
                throw new \Exception('请上传手机品牌图片');
            }
            //mod by lizenan 20180212 【后台需求】商城导览/商城导览添加/修改界面去除品牌图片Alt和手机品牌图片Alt 515 start
            //$brand_img_alt = $data['brand_img_alt'];
            //$brand_img_wap_alt = $data['brand_img_wap_alt'];
            $country_name = $data['country_name'];
            $country_img = $data['country_img'];
            $use_flg = $data['use_flg'];
            $url = $data['url'];
            $remark = $data['remark'];
            $brand_id = intval($data['brand_id']);
            $creator = $brand->getCreator();
            $oper_time = date('Y-m-d H:i:s');
            if ($brand_id){
                $brand = Brand::findOne($brand_id);
                if (!tools::arrayHasValue($brand,'id')){
                    throw new \Exception('品牌修改失败，品牌不存在');
                }
                $find_brand_name = Brand::find()->where('brand_name=:brand_name',[':brand_name'=>$brand_name])->asArray()->all();
                if (count($find_brand_name) > 1 || (count($find_brand_name) > 0 && intval($find_brand_name[0]['id']) != $brand_id)){
                    throw new \Exception('品牌名称已存在，请重新填写');
                }
                $brand->editor = $creator;
                $brand->edit_time = $oper_time;
                $mod = 'change';
            }else{
                $brand->creator = $creator;
                $brand->create_time = $oper_time;
                $mod = 'add';
            }
            $brand->brand_name = $brand_name;
            $brand->sort = $sort;
            $brand->country_name = $country_name;
            $brand->country_img = $country_img;
            $brand->brand_img = $brand_img;
            //$brand->brand_img_alt = $brand_img_alt;
            $brand->brand_img_wap = $brand_img_wap;
            //$brand->brand_img_wap_alt = $brand_img_wap_alt;
            $brand->url = $url;
            $brand->remark = $remark;
            $brand->use_flg = $use_flg;
            //mod by lizenan 20180212 【后台需求】商城导览/商城导览添加/修改界面去除品牌图片Alt和手机品牌图片Alt 515 end
            $brand->save();
            $id = $brand->attributes['id'];
            if (!$id){
                $this->retJson('操作失败，请重试',500);
            }
            $old_floor = $old_brand_category_id = [];
            switch ($mod){
                case 'change':
                    $old_brand_plus = BrandPlus::find()->select('id,type,floor_num,brand_category_id')->where('brand_id=:brand_id',['brand_id'=>$id])->asArray()->all();
                    if (is_array($old_brand_plus) && count($old_brand_plus) > 0)foreach ($old_brand_plus as $old_val){
                        if (intval($old_val['type']) == 1){
                            $old_floor[$old_val['id']] = $old_val['floor_num'];
                        }elseif (intval($old_val['type']) == 2){
                            $old_brand_category_id[$old_val['id']] = $old_val['brand_category_id'];
                        }
                    }
                    //筛选需要新增和删除的楼层
                    $floor_need_add = $floor_need_del = [];
                    if (count($old_floor) == 0){
                        $floor_need_add = $floor;
                    }else{
                        if (count($floor) > 0)foreach ($floor as $floor_val){
                            if (!in_array($floor_val, $old_floor)){
                                $floor_need_add[] = $floor_val;
                            }
                        }
                    }
                    if (count($floor) == 0){
                        $floor_need_del = array_keys($old_floor);
                    }else{
                        if (count($old_floor) > 0)foreach ($old_floor as $brand_plus_id=>$old_floor_val){
                            if (!in_array($old_floor_val, $floor)){
                                $floor_need_del[] = $brand_plus_id;
                            }
                        }
                    }
                    if (count($floor_need_del) > 0){
                        $true = BrandPlus::deleteAll(['id'=>$floor_need_del]);
                    }
                    //筛选需要新增和删除的品牌分类
                    $brand_category_need_add = $brand_category_need_del = [];
                    if (count($old_brand_category_id) == 0){
                        $brand_category_need_add = $brand_category;
                    }else{
                        if (count($brand_category) > 0)foreach ($brand_category as $brand_category_val){
                            if (!in_array($brand_category_val, $old_brand_category_id)){
                                $brand_category_need_add[] = $brand_category_val;
                            }
                        }
                    }
                    if (count($brand_category) == 0){
                        $brand_category_need_del = array_keys($old_brand_category_id);
                    }else{
                        if (count($old_brand_category_id) > 0)foreach ($old_brand_category_id as $brand_plus_id=>$old_brand_category_id_val){
                            if (!in_array($old_brand_category_id_val, $brand_category)){
                                $brand_category_need_del[] = $brand_plus_id;
                            }
                        }
                    }
                    $need_del = array_merge($floor_need_del,$brand_category_need_del);
                    if (count($need_del) > 0){
                        $true = BrandPlus::deleteAll(['id'=>$need_del]);
                    }
                    $floor = $floor_need_add;
                    $brand_category = $brand_category_need_add;
                case 'add':
                    $data_now = $data_add = [];
                    if (is_array($floor) && count($floor) > 0)foreach ($floor as $floor_val){
                        $data_now['brand_id'] = $id;
                        $data_now['type'] = 1;
                        $data_now['floor_num'] = $floor_val;
                        $data_now['floor'] = $GLOBALS['SHOPPING_MALL_FLOOR'][$floor_val];
                        $data_now['brand_category_id'] = null;
                        $data_now['brand_category_name'] = '';
                        $data_now['creator'] = $creator;
                        $data_now['create_time'] = $oper_time;
                        $data_add[] = $data_now;
                    }
                    if (is_array($brand_category) && count($brand_category) > 0){
                        $brand_cate = BrandCategory::find()->select('id,name')->where(['id'=>$brand_category])->asArray()->all();
                        $brand_cate = array_combine(array_column($brand_cate, 'id'), $brand_cate);
                        foreach ($brand_category as $brand_category_val){
                            $data_now['brand_id'] = $id;
                            $data_now['type'] = 2;
                            $data_now['floor_num'] = null;
                            $data_now['floor'] = '';
                            $data_now['brand_category_id'] = $brand_category_val;
                            $data_now['brand_category_name'] = tools::arrayHasValue($brand_cate,$brand_category_val) ? $brand_cate[$brand_category_val]['name'] : '';
                            $data_now['creator'] = $creator;
                            $data_now['create_time'] = $oper_time;
                            $data_add[] = $data_now;
                        }
                    }
                    if (count($data_add) > 0){
                        $fields = ['brand_id','type','floor_num','floor','brand_category_id','brand_category_name','creator','create_time'];
                        $res = Yii::$app->db->createCommand()->batchInsert('j_brand_plus', $fields,$data_add)->execute();
                        if(!$res){
                            throw new \Exception('操作失败');
                        }
                    }
                    break;
            }
            $transaction->commit();
            $this->retJson('操作成功',200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionBrandCategory()
    {
        return $this->render('brand-category');
    }
    
    public function actionGetBrandCategory(){
        $data = Yii::$app->request->post();
        $brand_category = BrandCategory::find()->where('use_flg='.BrandCategory::STATUS_ENABLE);
        $count = $brand_category->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $brand_category->offset($data['start'])->limit($data['length'])->orderBy(
            [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
        if (is_array($list) && count($list) > 0)foreach ($list as $key=>&$list_val){
            $list_val['num'] = $key+1;
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }
    
    public function actionDeleteBrandCategory(){
        $data = Yii::$app->request->post();
        $brand_category_id = $data['id'];
        $brand_count = BrandPlus::find()->where('brand_category_id='.$brand_category_id)->count();
        if($brand_count > 0){
            $this->retJson('此品牌分类已被使用，无法删除，请确认',500);
        }
        $data_now = array();
        $model = new BrandCategory();
        $data_now['use_flg'] = $model::STATUS_DISABLE;
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $hot_sale_where = ['id'=>$brand_category_id];
        $ret = $model::updateAll($data_now,$hot_sale_where);
        if(!$ret){
            $this->retJson('操作失败',500);
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionSaveBrandCategory(){
        $brand_catehory = new BrandCategory();
        $data = Yii::$app->request->post();
        $name = trim($data['name']);
        $sort = $data['sort'] ? $data['sort'] : 0;
        $creator = $brand_catehory->getCreator();
        $oper_time = date('Y-m-d H:i:s');
        if (!$name){
            $this->retJson('请填写品牌分类名称',500);
        }
        if (intval($data['id']) > 0){
            $brand_catehory = BrandCategory::findOne($data['id']);
            if (!tools::arrayHasValue($brand_catehory,'id')){
                $this->retJson('品牌分类不存在',500);
            }
            $brand_catehory->editor = $creator;
            $brand_catehory->edit_time = $oper_time;
            if ($name != $brand_catehory['name']){
                $find_brand_plus = BrandPlus::find()->where('brand_category_id=:brand_category_id',[':brand_category_id'=>$data['id']])->count();
                if ($find_brand_plus > 0){
                    BrandPlus::updateAll(['brand_category_name'=>$name],'brand_category_id='.$data['id']);
                }
            }
        }else{
            $brand_catehory->use_flg = $brand_catehory::STATUS_ENABLE;
            $brand_catehory->creator = $creator;
            $brand_catehory->create_time = $oper_time;
        }
        $brand_catehory->name = $name;
        $brand_catehory->sort = $sort;
        $brand_catehory->save();
        $brand_catehory_id = $brand_catehory->attributes['id'];
        if (!$brand_catehory_id){
            $this->retJson('操作失败，请重试',500);
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionFloorCategory(){
        $floor_category = FloorCategory::find()->asArray()->all();
        $floor_category_list = [];
        if (is_array($floor_category) && count($floor_category) > 0)foreach ($floor_category as $floor_category_val){
            $floor_category_list[$floor_category_val['floor_num']][$floor_category_val['category_grade']] = $floor_category_val;
        }
        $mall_floor = krsort($GLOBALS['SHOPPING_MALL_FLOOR']);
        return $this->render('floor-category',[
            'mall_floor'=>$GLOBALS['SHOPPING_MALL_FLOOR'],
            'floor_category'=>$floor_category_list
        ]);
    }
    
    public function actionSaveFloorCategory(){
        $floor_catehory = new FloorCategory();
        $data = Yii::$app->request->post();
        $id = intval($data['id']);
        $floor_num = intval($data['floor_num']);
        $floor = $GLOBALS['SHOPPING_MALL_FLOOR'][$floor_num];
        $category_grade = intval($data['category_grade']);
        $content = trim($data['content']);
        $creator = $floor_catehory->getCreator();
        $oper_time = date('Y-m-d H:i:s');
        if ($id > 0){
            $floor_catehory = FloorCategory::find()->where('id='.$id.' and category_grade='.$category_grade)->one();
            if (!tools::arrayHasValue($floor_catehory,'id')){
                $this->retJson('品牌分类不存在',500);
            }
            $floor_catehory->editor = $creator;
            $floor_catehory->edit_time = $oper_time;
        }else{
            $floor_catehory->floor_num = $floor_num;
            $floor_catehory->floor = $floor;
            $floor_catehory->creator = $creator;
            $floor_catehory->create_time = $creator;
        }
        $floor_catehory->category_grade = $category_grade;
        $floor_catehory->content = $content;
        $floor_catehory->save();
        $floor_catehory_id = $floor_catehory->attributes['id'];
        if (!$floor_catehory_id){
            $this->retJson('操作失败，请重试',500);
        }
        $this->retJson('操作成功',200);
    }
}